package com.hongri.recyclerview.service;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.app.Activity;

/**
 * Created by zhongyao on 2018/4/10.
 */

public class HongriContext {
    public static ArrayList<WeakReference<Activity>> activityLists = new ArrayList<>();

    public static ArrayList<WeakReference<Activity>> getActivityLists() {
        return activityLists;
    }

    public static void pushToActivityStack(Activity activity) {
        activityLists.add(new WeakReference<Activity>(activity));
    }

    public static void popFromActivityStack(Activity activity) {
        for (int x = 0; x < activityLists.size(); x++) {
            WeakReference<Activity> ref = activityLists.get(x);
            if (ref != null && ref.get() != null && ref.get() == activity) {
                activityLists.remove(ref);
            }
        }
    }

    public static Activity peekTopActivity() {
        if (activityLists != null && activityLists.size() > 0) {
            WeakReference<Activity> ref = activityLists.get(activityLists.size() - 1);
            if (ref != null && ref.get() != null) {
                return ref.get();
            }
        }
        return null;
    }

    public void clearActivityStack() {
        try {
            for (WeakReference<Activity> ref : activityLists) {
                if (ref != null && ref.get() != null && !ref.get().isFinishing()) {
                    ref.get().finish();
                }
            }
        } catch (Throwable e) {

        } finally {
            activityLists = null;
        }
    }
}
